// forwardRef作用：父组件获取子组件的实例获取DOM元素

import { useDispatch } from "react-redux"
import { Link, useNavigate } from "react-router-dom"
import { fetchLogin } from "../../store/modules/use"
import { useRef, forwardRef, useImperativeHandle } from "react"

const SonInput = forwardRef((props,ref)=>{
    // 实现聚焦逻辑
    const inputRef = useRef(null)
    const focusHandler = () =>{
        // inputRef.current.focus()
        console.log('这里是子组件方法')
    }
    // 把聚焦方法暴露出去
    useImperativeHandle(ref, ()=>{
        return {
            focusHandler
        }
    })
    return <input type='text' ref={ref}/>
})
const Login = () =>{
    const navigate = useNavigate()
    // 点击登录获取token
    const dispatch = useDispatch()
    const onFinish = (values) =>{
        console.log(values)
        // 触发异步action fetchLogin
        dispatch(fetchLogin(values))
        // 跳转到首页
        navigate('/')
    }
    const getUser = (event) =>{
        console.log('这里是通过ref获取账号信息：', event.target.value)
    }
    const sonPassword = useRef(null)
    const showRef = () =>{
        console.log('这里是直接获取密码：',sonPassword.current.value)
        console.log('这里是直接获取密码DOM的聚焦方法：',sonPassword.current.focusHandler)
        sonPassword.current.focusHandler()
    }
    return <div>
        <div>账号：<input onChange={getUser}></input></div>
        <div>密码：<SonInput ref={sonPassword}/></div>
        <div>
            <button onClick={()=>showRef()}>获取密码值</button>
        </div>
        <div>
            <button onClick={()=>onFinish({name:'1',password:'123456'})}>获取token</button>
        </div>
        <div>
            <button onClick={()=>navigate('/shop')}>登录</button>
            <Link to="/shop">跳转到购物</Link>
        </div>
        <div>
            <button onClick={()=>navigate('/shop?id=100&name=zs')}>登录(传参)</button>
            <Link to="/shop?id=100&name=zs">跳转到购物(传参)</Link>
        </div>
        <div>
            <Link to="/my/100/ll">跳转到我的(传参)</Link>
        </div>
    </div>
}
export default Login